class TabSlider {

	constructor(options) {
		this.container = document.querySelector(options.container);
		this.nav = document.querySelector(options.nav);
		this.content = document.querySelector(options.content);
		this.data = options.data || [];
		this.currentIndex = options.currentIndex || 0;
		this.onChange = options.onChange || function() {}
		this.init();
		this.bindEvents();
	}

	init() {
		// 创建导航标签
		this.nav.innerHTML = this.data.map((item, index) =>
			`<div class="tab-item ${this.currentIndex === index ? 'active' : ''}" 
                  data-index="${index}" data-key="${item.key}">${item.label}</div>`
		).join('');

		// 创建下划线
		this.underline = document.createElement('div');
		this.underline.className = 'tab-underline';
		this.nav.appendChild(this.underline);

		this.updateUnderline();
	}

	bindEvents() {
		this.nav.addEventListener('click', (e) => {
			const tabItem = e.target.closest('.tab-item');
			if (!tabItem) return;

			const index = parseInt(tabItem.dataset.index);
			if (index === this.currentIndex) return;

			this.switchTab(index);
			this.onChange(index);
		});
	}

	switchTab(index) {
		// 更新导航状态
		const prevTab = this.nav.querySelector('.tab-item.active');
		const nextTab = this.nav.querySelector(`.tab-item[data-index="${index}"]`);

		prevTab.classList.remove('active');
		nextTab.classList.add('active');

		// 更新内容状态
		// const prevContent = this.content.querySelector('.content-item.active');
		// const nextContent = this.content.querySelector(`.content-item:nth-child(${index + 1})`);

		// prevContent.classList.remove('active');
		// nextContent.classList.add('active');

		this.currentIndex = index;
		this.updateUnderline();
		this.scrollToTab();
	}

	updateUnderline() {
		const activeTab = this.nav.querySelector('.tab-item.active');
		if (!activeTab) return;

		this.underline.style.width = `${activeTab.offsetWidth}px`;
		this.underline.style.left = `${activeTab.offsetLeft}px`;
	}

	scrollToTab() {
		const activeTab = this.nav.querySelector('.tab-item.active');
		this.container.scrollTo({
			left: activeTab.offsetLeft - (this.container.offsetWidth - activeTab.offsetWidth) / 2,
			behavior: 'smooth'
		});
	}

	updateData(newData) {
		this.data = newData;
		this.currentIndex = 0;
		this.init();
	}
}
